package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizExceptionEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zr
 * @date 2022/9/7 20:37
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    /**
     * 数据校验处理异常
     *
     * @param validException
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException validException) {
        BindingResult bindingResult = validException.getBindingResult();
        Map<String, String> resultMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item -> {
            resultMap.put(item.getDefaultMessage(), item.getField());
        });
        log.error("数据校验出现问题{},异常类型{}", validException.getMessage(), validException.getClass());
        return R.error(BizExceptionEnum.VALID_EXCEPTION.getCode(), BizExceptionEnum.VALID_EXCEPTION.getMsg()).put("data", resultMap);
    }

//    @ExceptionHandler(value = Throwable.class)
//    public R handleException(Throwable throwable) {
//        log.error("未知异常{},异常类型{}", throwable.getMessage(), throwable.getClass());
//        return R.error(BizExceptionEnum.UNKNOW_EXEPTION.getCode(), BizExceptionEnum.UNKNOW_EXEPTION.getMsg());
//    }
}
